package br.com.vti.leilao.view.bean;

import br.com.vti.leilao.model.business.exception.ApplicationException;
import br.com.vti.leilao.model.entity.Model;
import br.com.vti.leilao.view.util.JsfManager;

import java.util.ArrayList;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.UIComponent;
import javax.faces.component.UIForm;
import javax.faces.event.ActionEvent;

import org.primefaces.event.CloseEvent;

/**
 * Classe abstrata que herda de BeanImpl e sobrescreve o método remover para
 * adequá-lo a aplicação concessao de beneficio.
 * 
 * @param <E> entidade
 * @param <X> exceção extends ApplicationException 
 * @author Ednardo Rubens
 * @version 0.1
 */
public abstract class CommonBean<E extends Model<? extends Number>, X extends ApplicationException>
        extends BeanImpl<E, X> {

    private static final long serialVersionUID = 125673784459251974L;
    
    @ManagedProperty("#{jsfManager}")
    private JsfManager jsfManager;
    
    public JsfManager getJsfManager() {
        return jsfManager;
    }

    public void setJsfManager(JsfManager jsfManager) {
        this.jsfManager = jsfManager;
    }

    public void resetCadastro(ActionEvent event) {
        try {
            getJsfManager().reset(event);
            setEntidade(getEntityClass().newInstance());
            instanciarObjetosFilhos(getEntidade());
        } catch (Exception e) {
            getLogger().error(e);
        }
    }

    public void resetPesquisa(ActionEvent event) {
        try {
            getJsfManager().reset(event);
            setEntidadePesquisa(getEntityClass().newInstance());
            instanciarObjetosFilhos(getEntidadePesquisa());
            setListaEntidade(new ArrayList<E>());
        } catch (Exception e) {
            getLogger().error(e);
        }
    }

    @Override
    public void remover() {
        super.remover();
        try {
            setEntidade(getEntityClass().newInstance());
        } catch (Exception e) {
            getLogger().error(e);
        }
    }

    @Override
    @PostConstruct
    public void init() {
        super.init();
    }
    
    /**
     * Limpa formulário de um dialog ao fechar.
     * @param event evento de fechar o dialog.
     */
    public void closeListener(CloseEvent event) {
        UIForm form = getJsfManager().findForm(event.getComponent(), false);
        UIComponent child = form.getChildren().get(0);
        resetCadastro(new ActionEvent(child));
        resetPesquisa(new ActionEvent(child));
    }
    
}
